package pages;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import templates.Template;

public class ErrorPage {

	private static final String templateName = "error";

	/**
	 * Creates page with errorText inside
	 * 
	 * @param errorText
	 * @param userLogin
	 * @return string containing the page
	 * @throws InternalErrorException
	 */
	public static String generateErrorPage(String errorText, String userLogin)
			throws InternalErrorException {
		if (errorText == null) {
			return "";
		}
		Template errorTemplate = new Template(templateName);
		errorTemplate.addChange("error", errorText);
		return errorTemplate.createPage("Error", userLogin);
	}

	/**
	 * Tries to generate error page and sends it.
	 * Sends raw errorText if couldn't generate the page  
	 * @param errorText
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public static void printErrorPage(String errorText,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			String userLogin = LMUtils.getUserLogin(request);
			response.getWriter().print(
					ErrorPage.generateErrorPage(errorText, userLogin));
		} catch (InternalErrorException e1) {
			response.getWriter().print(errorText + "<br/>" + e1.getMessage());
		}
	}
}
